package com.linko.soundrecorder;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.linko.soundrecorder.com.linko.soundrecorder.emoji.Emojicon;
import com.linko.soundrecorder.com.linko.soundrecorder.emoji.Nature;
import com.linko.soundrecorder.com.linko.soundrecorder.emoji.Objects;
import com.linko.soundrecorder.com.linko.soundrecorder.emoji.People;
import com.linko.soundrecorder.com.linko.soundrecorder.emoji.Places;
import com.linko.soundrecorder.com.linko.soundrecorder.emoji.Symbols;

import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;

public class SoundRecorder extends Activity implements SideslipFragment.NavigationDrawerCallbacks, View.OnClickListener, Recorder.OnRecordListener, TextWatcher {
    private final String TAG = SoundRecorder.class.getSimpleName();
    private ActionBar mActionBar;
    private DrawerLayout mDrawerLayout;
    private View mSideslipView;
    private DrawerArrowDrawable mArrowDrawable;
    private ActionBarDrawerToggle mActionBarDrawerToggle;
    private long mLastClickTime;
    private ImageView mVumeterImg;
    private LinearLayout mTimer;
    private Button mAddNewRecordBtn;
    private Button mFinishRecordBtn;
    private Button mStartRecordBtn;
    private Button mStopRecordBtn;
    private Button mDeleteRecordBtn;
    private Button mPauseRecordBtn;
    private Button mPlayRecordBtn;
    private EditText mNameView;

    public static final String MAX_FILE_SIZE_KEY = "max_file_size";

    private Recorder mRecorder;

    private RecordHandler mHandler;

    private final int[] mVUMeturImgIds = new int[]{
            R.drawable.ic_recorder_class0, R.drawable.ic_recorder_class1,
            R.drawable.ic_recorder_class2, R.drawable.ic_recorder_class3,
            R.drawable.ic_recorder_class4, R.drawable.ic_recorder_class5,
            R.drawable.ic_recorder_class6};

    private String mTimerFormat;

    private HomeKeyReceiver mHoneKeyReceiver;

    private LocalFileNameFilter mFileNameFilter;

    private String mPreChangedFileName = "";

    private View mMediaPlayerProgress;
    private SeekBar mPlaySeekBar;
    private static final int SEEK_BAR_MAX = 10000;

    private static AlertDialog.Builder mAlertDialog = null;
    private static final int RECORD_NAME_TEXT_LIMIT = 80;

    private SideslipFragment mSideslipFragment;

    private Emojicon[][] mEmojis = {Nature.DATA, Objects.DATA, People.DATA, Places.DATA, Symbols.DATA};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        setContentView(R.layout.activity_sound_recorder);
        mRecorder = new Recorder(this, savedInstanceState);
        // only support 3gpp/amr format
        boolean isFormatSupport = mRecorder.processIntent(getIntent());
        if (!isFormatSupport) {
            setResult(Activity.RESULT_CANCELED);
            Toast.makeText(this, R.string.not_support_formart, Toast.LENGTH_LONG).show();
            finish();
        }

        initViews();
        initActionBarDrawer();

        mTimerFormat = getResources().getString(R.string.timer_format);
        mHandler = new RecordHandler();
        mRecorder.setOnRecordListener(this);
    }

    private void initViews() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mSideslipView = findViewById(R.id.side_slip_container);
        mVumeterImg = (ImageView) findViewById(R.id.vumeter_img);
        mTimer = (LinearLayout) findViewById(R.id.timer_layout);
        mNameView = (EditText) findViewById(R.id.file_name_view);
        mMediaPlayerProgress = findViewById(R.id.play_seek_bar_layout);
        mPlaySeekBar = (SeekBar) findViewById(R.id.play_seek_bar);
        mPlaySeekBar.setMax(SEEK_BAR_MAX);
        mPlaySeekBar.setOnSeekBarChangeListener(mSeekBarChangeListener);
        mAddNewRecordBtn = (Button) findViewById(R.id.btn_add);
        mFinishRecordBtn = (Button) findViewById(R.id.btn_finish);
        mDeleteRecordBtn = (Button) findViewById(R.id.btn_delete);
        mStartRecordBtn = (Button) findViewById(R.id.btn_start);
        mStopRecordBtn = (Button) findViewById(R.id.btn_stop);
        mPauseRecordBtn = (Button) findViewById(R.id.btn_pause);
        mPlayRecordBtn = (Button) findViewById(R.id.btn_play);
        mAddNewRecordBtn.setOnClickListener(this);
        mFinishRecordBtn.setOnClickListener(this);
        mDeleteRecordBtn.setOnClickListener(this);
        mStartRecordBtn.setOnClickListener(this);
        mStopRecordBtn.setOnClickListener(this);
        mPauseRecordBtn.setOnClickListener(this);
        mPlayRecordBtn.setOnClickListener(this);
        mNameView.addTextChangedListener(this);
        maxLengthFilter(this, mNameView, RECORD_NAME_TEXT_LIMIT);
        mFileNameFilter = new LocalFileNameFilter();
        mSideslipFragment = new SideslipFragment();
        getFragmentManager().beginTransaction().add(R.id.side_slip_container, mSideslipFragment).commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mRecorder.onResume();
        if (!mRecorder.syncStateWithService()) {
            if (mRecorder.getRecordFileSize() == 0) {
                mRecorder.reset();
            }
        }
        registerHomeKeyListener();
        updateUi();
        if (RecordService.isRecording()) {
            mHandler.sendEmptyMessageDelayed(COMMAND_UPDATE_TIMER, 500);
            mHandler.sendEmptyMessageDelayed(COMMAND_UPDATE_VUMETUR, 100);
        }
        hideNotification();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getFragmentManager().beginTransaction().remove(mSideslipFragment).commit();
        setContentView(R.layout.activity_sound_recorder);
        initViews();
        if (!mRecorder.syncStateWithService()) {
            if (mRecorder.getRecordFileSize() == 0) {
                mRecorder.reset();
            }
        }
        updateUi();
    }

    @Override
    public void onDestroy() {
        mRecorder.onDestory();
        mRecorder = null;
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        mRecorder.onPause();
        unRegisterHomeKeyListener();
        mHandler.removeMessages(COMMAND_UPDATE_TIMER);
        mHandler.removeMessages(COMMAND_UPDATE_VUMETUR);
        mHandler.removeMessages(COMMAND_UPDATE_PROGRESS);
    }

    private void updateUi() {
        updateButtonState();
        updateTimer();
        updateProgress();
        updateVUMeterView();
        mNameView.setText(Recorder.getRecordFileName());
    }

    private void registerHomeKeyListener() {
        mHoneKeyReceiver = new HomeKeyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(mHoneKeyReceiver, filter);
    }

    private void unRegisterHomeKeyListener() {
        if (mHoneKeyReceiver != null) {
            unregisterReceiver(mHoneKeyReceiver);
        }
    }

    private final int COMMAND_UPDATE_TIMER = 0;
    private final int COMMAND_UPDATE_VUMETUR = 1;
    private final int COMMAND_UPDATE_PROGRESS = 2;

    private class RecordHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case COMMAND_UPDATE_TIMER: {
                    updateTimer();
                    break;
                }
                case COMMAND_UPDATE_VUMETUR: {
                    updateVUMeterView();
                    break;
                }
                case COMMAND_UPDATE_PROGRESS: {
                    updateProgress();
                    break;
                }
            }
        }
    }

    private void updateVUMeterView() {
        int state = mRecorder.getRecorderState();
        if (mVumeterImg.getVisibility() == View.VISIBLE
                && mRecorder.getRecorderState() == Recorder.RECORDING_STATE) {
            int vuSize = mVUMeturImgIds.length * mRecorder.getMaxAmplitude() / 32768;
            if (vuSize > mVUMeturImgIds.length) {
                vuSize = mVUMeturImgIds.length;
            }
            mVumeterImg.setImageResource(mVUMeturImgIds[vuSize]);
        } else {
            mVumeterImg.setImageResource(mVUMeturImgIds[0]);
        }
        boolean ongoing = state == Recorder.RECORDING_STATE || state == Recorder.PLAYING_STATE;
        if (ongoing) {
            mHandler.removeMessages(COMMAND_UPDATE_VUMETUR);
            mHandler.sendEmptyMessageDelayed(COMMAND_UPDATE_VUMETUR, 100);
        }
    }

    private void updateTimer() {
        int state = mRecorder.getRecorderState();
        long time = mRecorder.getProgress();
        String timeStr = String.format(mTimerFormat, time / 60, time % 60);
        timeStr = timeStr.replaceAll("[^0-9:]+", "");
        mTimer.removeAllViews();
        System.gc();// release image resource.
        for (int i = 0; i < timeStr.length(); i++) {
            mTimer.addView(getTimerImage(timeStr.charAt(i)));
        }

        if (state == Recorder.IDLE_STATE) {
            setTimerView(0);
        }

        boolean ongoing = state == Recorder.RECORDING_STATE || state == Recorder.PLAYING_STATE;
        if (ongoing) {
            mHandler.removeMessages(COMMAND_UPDATE_TIMER);
            mHandler.sendEmptyMessageDelayed(COMMAND_UPDATE_TIMER, 100);
        }
    }

    private void updateProgress() {
        if (mMediaPlayerProgress.getVisibility() == View.INVISIBLE) {
            return;
        }
        long totalTime = mRecorder.getRecordTotalTime();
        float percent = mRecorder.getplayPercentage();
        long currentTime = (long) (totalTime * percent);
        int progress = (int) (percent * SEEK_BAR_MAX);
        mPlaySeekBar.setProgress(progress);

        TextView totalaTimeTv = (TextView) mMediaPlayerProgress.findViewById(R.id.total_time);
        TextView currentTimeTv = (TextView) mMediaPlayerProgress.findViewById(R.id.current_time);
        String totalTimeStr = String.format(mTimerFormat, totalTime / 60, totalTime % 60);
        String currentTimeStr = String.format(mTimerFormat, currentTime / 60, currentTime % 60);
        totalaTimeTv.setText(totalTimeStr);
        currentTimeTv.setText(currentTimeStr);

        int state = mRecorder.getRecorderState();
        boolean ongoing = state == Recorder.PLAYING_STATE;
        if (ongoing) {
            mHandler.removeMessages(COMMAND_UPDATE_PROGRESS);
            mHandler.sendEmptyMessageDelayed(COMMAND_UPDATE_PROGRESS, 20);
        }
    }

    private ImageView getTimerImage(char number) {
        ImageView image = new ImageView(this);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        if (number != ':') {
            image.setBackgroundResource(R.drawable.background_number);
        }
        switch (number) {
            case '0':
                image.setImageResource(R.drawable.number_0);
                break;
            case '1':
                image.setImageResource(R.drawable.number_1);
                break;
            case '2':
                image.setImageResource(R.drawable.number_2);
                break;
            case '3':
                image.setImageResource(R.drawable.number_3);
                break;
            case '4':
                image.setImageResource(R.drawable.number_4);
                break;
            case '5':
                image.setImageResource(R.drawable.number_5);
                break;
            case '6':
                image.setImageResource(R.drawable.number_6);
                break;
            case '7':
                image.setImageResource(R.drawable.number_7);
                break;
            case '8':
                image.setImageResource(R.drawable.number_8);
                break;
            case '9':
                image.setImageResource(R.drawable.number_9);
                break;
            case ':':
                image.setImageResource(R.drawable.colon);
                break;
        }
        image.setLayoutParams(lp);
        return image;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        mPreChangedFileName = charSequence.toString();
    }

    @Override
    public void onTextChanged(CharSequence text, int start, int i2, int lengthAfter) {
        String name = text.toString();
        if (mFileNameFilter != null && !TextUtils.isEmpty(name)) {
            boolean isAccept = mFileNameFilter.accept(null, text.toString());
            String addStr = name.substring(start, start + lengthAfter);
            for (int i = 0; i < mEmojis.length; i++) {
                for (int j = 0; j < mEmojis[i].length; j++) {
                    String emoji = mEmojis[i][j].getEmoji();
                    if (TextUtils.equals(emoji, addStr)) {
                        isAccept = false;
                        break;
                    }
                }
            }
            if (!isAccept) {
                Toast.makeText(this, R.string.not_access_file_name, Toast.LENGTH_LONG).show();
                name = name.replace(name.subSequence(start, start + lengthAfter), "");
                if (TextUtils.isEmpty(name)) {
                    mNameView.setText(mPreChangedFileName);
                    mNameView.setSelection(mPreChangedFileName.length());
                } else {
                    mNameView.setText(name);
                    mNameView.setSelection(start);
                }
            }
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {
        mRecorder.resetFileName(editable.toString());
    }

    @Override
    public void onClick(View view) {
        TelephonyManager teleManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (teleManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
            Toast.makeText(this, getString(R.string.offhook_record_warn), Toast.LENGTH_LONG)
                    .show();
            return;
        }
        if (System.currentTimeMillis() - mLastClickTime < 300) {
            // in order to avoid user click bottom too quickly
            return;
        }
        if (view.getId() == R.id.btn_stop && System.currentTimeMillis() - mLastClickTime < 1200) {
            // it seems that the media recorder is not robust enough
            // sometime it crashes when stop recording right after starting
            return;
        }
        mLastClickTime = System.currentTimeMillis();
        switch (view.getId()) {
            case R.id.btn_add: {
                mRecorder.reset();
                break;
            }
            case R.id.btn_finish: {
                finish();
                break;
            }
            case R.id.btn_delete: {
                showDeleteConfirmDialog();
                break;
            }
            case R.id.btn_start: {
                mRecorder.startRecord();
                break;
            }
            case R.id.btn_stop: {
                mRecorder.stopRecord();
                break;
            }
            case R.id.btn_pause: {
                mRecorder.pausePlay();
                break;
            }
            case R.id.btn_play: {
                mRecorder.startPlay(mRecorder.getplayPercentage());
                break;
            }
        }
    }

    private void updateButtonState() {
        mNameView.setEnabled(false);
        mAddNewRecordBtn.setEnabled(true);
        mFinishRecordBtn.setEnabled(false);
        mDeleteRecordBtn.setEnabled(false);

        mAddNewRecordBtn.setVisibility(View.GONE);
        mFinishRecordBtn.setVisibility(View.GONE);
        mStartRecordBtn.setVisibility(View.GONE);
        mStopRecordBtn.setVisibility(View.GONE);
        mPauseRecordBtn.setVisibility(View.GONE);
        mPlayRecordBtn.setVisibility(View.GONE);
        mMediaPlayerProgress.setVisibility(View.VISIBLE);

        long recordFileSize = mRecorder.getRecordFileSize();
        if (mRecorder.isRequestRecord()) {
            mFinishRecordBtn.setVisibility(View.VISIBLE);
            mFinishRecordBtn.setEnabled(recordFileSize > 0);
        } else {
            mAddNewRecordBtn.setVisibility(View.VISIBLE);
        }

        int state = mRecorder.getRecorderState();
        switch (state) {
            case Recorder.IDLE_STATE: {
                mNameView.setEnabled(true);
                mPlayRecordBtn.setVisibility(recordFileSize > 0 ? View.VISIBLE : View.GONE);
                mStartRecordBtn.setVisibility(recordFileSize > 0 ? View.GONE : View.VISIBLE);
                mDeleteRecordBtn.setEnabled(recordFileSize > 0);
                mMediaPlayerProgress.setVisibility(recordFileSize > 0 ? View.VISIBLE : View.INVISIBLE);
                mPlaySeekBar.setProgress(0);
                updateProgress();
                break;
            }
            case Recorder.RECORDING_STATE: {
                mAddNewRecordBtn.setEnabled(false);
                mFinishRecordBtn.setEnabled(false);
                mStopRecordBtn.setVisibility(View.VISIBLE);
                mMediaPlayerProgress.setVisibility(View.INVISIBLE);
                break;
            }
            case Recorder.PLAYING_STATE: {
                mPauseRecordBtn.setVisibility(View.VISIBLE);
                updateProgress();
                break;
            }
            case Recorder.PLAYING_PAUSED_STATE: {
                mPlayRecordBtn.setVisibility(View.VISIBLE);
                mDeleteRecordBtn.setEnabled(recordFileSize > 0);
                break;
            }
        }
    }

    @Override
    public void onStateChanged(int state) {
        Log.i(TAG, "onStateChanged:" + state);
        updateUi();
        if (mRecorder.getRecorderState() == Recorder.IDLE_STATE) {
            setResult();
        }
    }

    public void setResult() {
        String filePath = mRecorder.getFileFullName();
        Uri fileUri = Uri.fromFile(new File(filePath));
        setResult(Activity.RESULT_OK, new Intent().setData(fileUri));
    }

    @Override
    public void onError(int error) {
        Log.i(TAG, "onError:" + error);
        Toast.makeText(this, R.string.record_occur_error, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onNameChanged(String newName) {
        Log.i(TAG, "onNameChanged:" + newName);
        mNameView.setText(newName);
        setResult();// re-set result data when name changed.
    }

    public class HomeKeyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            if (!RecordService.isRecording()) {
                return;
            }
            if (TextUtils.equals(intent.getAction(), Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra("reason");
                if (TextUtils.equals(reason, "homekey") || TextUtils.equals(reason, "recentapps")) {
                    if (mRecorder.getRecorderState() == Recorder.RECORDING_STATE) {
                        if (mRecorder.getMaxLimitFileSize() != -1) {
                            Toast.makeText(context,
                                    getString(R.string.not_support_background_record_warn),
                                    Toast.LENGTH_LONG).show();
                            mRecorder.stopRecord();
                            finish();
                        } else {
                            showNotification();
                        }
                    }
                }
            }
        }
    }

    public void showNotification() {
        mRecorder.showNotification();
    }

    public void hideNotification() {
        mRecorder.hideNotification();
    }

    private class LocalFileNameFilter implements FilenameFilter {
        Pattern pattern;
        String regex = "[^\\\\/*:\"&<>|]+";

        public LocalFileNameFilter() {
            pattern = Pattern.compile(regex);
        }

        @Override
        public boolean accept(File dir, String filename) {
            return pattern.matcher(filename).matches();
        }

    }

    private SeekBar.OnSeekBarChangeListener mSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mRecorder.startPlay((float) seekBar.getProgress() / SEEK_BAR_MAX);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            mRecorder.pausePlay();
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                setTimerView(((float) progress) / SEEK_BAR_MAX);
            }
        }
    };

    private void setTimerView(float percentage) {
        long time = (long) (percentage * mRecorder.getRecordTotalTime());
        String timeStr = String.format(mTimerFormat, time / 60, time % 60);
        timeStr = timeStr.replaceAll("[^0-9:]+", "");
        mTimer.removeAllViews();
        System.gc();
        for (int i = 0; i < timeStr.length(); i++) {
            mTimer.addView(getTimerImage(timeStr.charAt(i)));
        }
    }

    public static void maxLengthFilter(final Context context, final EditText editText,
                                       final int maxLength) {
        InputFilter[] contentFilters = new InputFilter[1];
        contentFilters[0] = new InputFilter.LengthFilter(maxLength) {
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                int keep = maxLength - (dest.length() - (dend - dstart));
                if (keep <= 0) {
                    showWarningDialog(context, maxLength);
                    return "";
                } else if (keep >= end - start) {
                    return null;
                } else {
                    if (keep < source.length()) {
                        showWarningDialog(context, maxLength);
                    }
                    return source.subSequence(start, start + keep);
                }
            }
        };
        editText.setFilters(contentFilters);
    }

    private static void showWarningDialog(final Context context, int maxLength) {
        if (mAlertDialog != null)
            return;

        mAlertDialog = new AlertDialog.Builder(context);
        mAlertDialog.setTitle(R.string.max_input_title)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setMessage(context.getString(R.string.text_input_max_limit, maxLength))
                .setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        })
                .show()
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        mAlertDialog = null;
                        return;
                    }
                });
        mAlertDialog.create().getWindow()
                .setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
    }

    private void showDeleteConfirmDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(SoundRecorder.this,
                AlertDialog.THEME_HOLO_LIGHT);
        dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
        dialogBuilder.setTitle(R.string.delete_dialog_title);
        dialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                boolean isDeleted = mRecorder.delete();
                if (isDeleted) {
                    mRecorder.reset();
                }
            }
        });
        dialogBuilder.setNegativeButton(android.R.string.cancel, null);
        dialogBuilder.setCancelable(false);
        dialogBuilder.show();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(MAX_FILE_SIZE_KEY, mRecorder.getMaxLimitFileSize());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        if (mDrawerLayout.isDrawerOpen(mSideslipView)) {
            mDrawerLayout.closeDrawer(mSideslipView);
        }
        Log.i(TAG, "onNavigationDrawerItemSelected:" + position);
        Intent intent = new Intent();
        switch (position) {
            case SideslipFragment.ITEM_FIELS: {
                intent.setClass(getApplicationContext(), RecordFileListActivity.class);
                break;
            }
            case SideslipFragment.ITEM_SETTINGS: {
                if (RecordService.isRecording()) {
                    Toast.makeText(this, R.string.warm_stop_record_and_setup, Toast.LENGTH_LONG).show();
                    return;
                }
                intent.setClass(getApplicationContext(), SettingsActivity.class);
                break;
            }
            case SideslipFragment.ITEM_ABOUT: {
                intent.setClass(getApplicationContext(), AboutOrganization.class);
                break;
            }
            case SideslipFragment.ITEM_FEEDBACK: {
                intent.setClass(getApplicationContext(), FeedbackActivity.class);
                break;
            }
        }
        startActivity(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {
            if (mDrawerLayout.isDrawerOpen(mSideslipView)) {
                mDrawerLayout.closeDrawer(mSideslipView);
            } else {
                mDrawerLayout.openDrawer(mSideslipView);
            }
        }
        return true;
    }

    private void initActionBarDrawer() {
        mActionBar = getActionBar();
        mActionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.title_bar_bg_color));
        mActionBar.setDisplayHomeAsUpEnabled(true);
        mActionBar.setDisplayShowHomeEnabled(false);
        mActionBar.setHomeButtonEnabled(true);
        mArrowDrawable = new DrawerArrowDrawable(this) {
            @Override
            public boolean isLayoutRtl() {
                return false;
            }
        };

        mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mArrowDrawable, R.string.drawer_open, R.string.drawer_close) {
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
        mActionBarDrawerToggle.syncState();
    }

    @Override
    public void onBackPressed() {
        long time = System.currentTimeMillis();
        if (time - mLastClickTime > 2000) {
            Toast.makeText(getApplicationContext(), R.string.click_again_exit, Toast.LENGTH_LONG).show();
            mLastClickTime = time;
            return;
        } else {
            if (RecordService.isRecording()) {
                showNotification();
            }
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_MENU) {
            if (mDrawerLayout.isDrawerOpen(mSideslipView)) {
                mDrawerLayout.closeDrawer(mSideslipView);
            } else {
                mDrawerLayout.openDrawer(mSideslipView);
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
